package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
           /* if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }*/
            for (Mapper.MappedHost host : mapper.getHosts()) {
                if (host.getName().equals(request.getHostName())) {
                    for (Mapper.MappedContext context : host.getContexts()) {
                        if (context.getName().equals(request.getAppName())) {
                            for (Mapper.MappedWrapper wrapper : context.getWrappers()) {
                                if (wrapper.getName().equals(request.getUrl())) {
                                    wrapper.getObject().getServlet().service(request,response);
                                    socket.close();
                                    return;
                                }
                            }
                        }
                    }
                }

            }
            response.outputHtml(request.getUrl());
            socket.close();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
